<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传文件到RAGFlow</title>
    <style>
        .drop-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin: 20px;
            background-color: #fafafa;
            transition: border-color 0.3s;
        }

        .drop-area.dragover {
            border-color: #007bff;
            background-color: #e6f2ff;
        }

        .file-list {
            margin: 20px 0;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border: 1px solid #eee;
            margin: 5px 0;
            border-radius: 5px;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background-color: #007bff;
            width: 0%;
            transition: width 0.3s;
        }

        .upload-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .upload-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
        }

        .status.success {
            background-color: #d4edda;
            color: #155724;
        }

        .status.error {
            background-color: #f8d7da;
            color: #721c24;
        }

        .uploaded-files {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #ccc;
        }

        .uploaded-files h3 {
            margin-bottom: 10px;
        }

        .uploaded-file-item {
            padding: 5px 10px;
            background-color: #f0f8ff;
            margin: 3px 0;
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <h1>上传文件到RAGFlow</h1>

    <div id="dropArea" class="drop-area">
        <p>拖拽文件到此处或点击选择文件</p>
        <p>支持格式: Word(.doc, .docx), Excel(.xls, .xlsx), PDF(.pdf), TXT(.txt)</p>
        <input type="file" id="fileInput" multiple style="display: none;">
        <button onclick="document.getElementById('fileInput').click()">选择文件</button>
    </div>

    <div id="fileList" class="file-list"></div>

    <button id="uploadBtn" class="upload-btn" disabled>上传文件</button>

    <div id="status" class="status" style="display: none;"></div>

    <div id="uploadedFiles" class="uploaded-files">
        <h3>上传历史</h3>
        <div id="uploadedFilesList"></div>
    </div>

    <script>
        let filesToUpload = [];
        // 新增：存储已上传文件的数组
        let uploadedFiles = [];
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const uploadBtn = document.getElementById('uploadBtn');
        const statusDiv = document.getElementById('status');
        // 新增：上传历史列表元素
        const uploadedFilesList = document.getElementById('uploadedFilesList');

        // 允许的文件类型
        const allowedTypes = [
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/pdf',
            'text/plain'
        ];

        const allowedExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.pdf', '.txt'];

        // 拖拽事件处理
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropArea.classList.add('dragover');
        }

        function unhighlight() {
            dropArea.classList.remove('dragover');
        }

        // 处理文件拖拽放下
        dropArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles(files);
        }

        // 处理文件选择
        fileInput.addEventListener('change', function () {
            handleFiles(this.files);
        });

        function handleFiles(files) {
            [...files].forEach(file => {
                // 检查文件类型
                if (isFileAllowed(file)) {
                    filesToUpload.push(file);
                } else {
                    showStatus(`文件 ${file.name} 格式不支持，已忽略。`, 'error');
                }
            });
            updateFileList();
        }

        function isFileAllowed(file) {
            // 检查MIME类型
            if (allowedTypes.includes(file.type)) {
                return true;
            }

            // 检查文件扩展名
            const fileName = file.name.toLowerCase();
            return allowedExtensions.some(ext => fileName.endsWith(ext));
        }

        function updateFileList() {
            fileList.innerHTML = '';

            filesToUpload.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div>
                        <strong>${file.name}</strong> (${formatFileSize(file.size)})
                    </div>
                    <div id="progress-${index}" style="display: none; width: 300px;">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progress-fill-${index}"></div>
                        </div>
                    </div>
                    <button onclick="removeFile(${index})">移除</button>
                `;
                fileList.appendChild(fileItem);
            });

            uploadBtn.disabled = filesToUpload.length === 0;
        }

        function removeFile(index) {
            filesToUpload.splice(index, 1);
            updateFileList();
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 上传文件
        uploadBtn.addEventListener('click', uploadFiles);

        function uploadFiles() {
            if (filesToUpload.length === 0) return;

            uploadBtn.disabled = true;
            showStatus('正在上传文件...', 'info');

            // 逐个上传文件
            uploadFilesSequentially(0);
        }

        function uploadFilesSequentially(index) {
            if (index >= filesToUpload.length) {
                // 新增：上传完成后将文件名存入上传历史并清空上传列表
                filesToUpload.forEach(file => {
                    if (!uploadedFiles.includes(file.name)) {
                        uploadedFiles.push(file.name);
                    }
                });
                filesToUpload = [];
                updateFileList();
                updateUploadedFilesList();
                showStatus('所有文件上传完成！', 'success');
                uploadBtn.disabled = false;
                return;
            }

            const file = filesToUpload[index];
            const progressContainer = document.getElementById(`progress-${index}`);
            const progressFill = document.getElementById(`progress-fill-${index}`);

            // 确保进度条容器显示
            progressContainer.style.display = 'block';

            const formData = new FormData();
            formData.append('file', file);

            const xhr = new XMLHttpRequest();

            // 监听上传进度
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressFill.style.width = percentComplete + '%';
                }
            });

            // 处理上传完成
            xhr.addEventListener('load', function () {
                if (xhr.status === 200) {
                    // 继续上传下一个文件
                    setTimeout(() => uploadFilesSequentially(index + 1), 500);
                } else {
                    showStatus(`文件 ${file.name} 上传失败: ${xhr.statusText}`, 'error');
                    uploadBtn.disabled = false;
                }
            });

            // 处理上传错误
            xhr.addEventListener('error', function () {
                showStatus(`文件 ${file.name} 上传出错`, 'error');
                uploadBtn.disabled = false;
            });

            // 发送请求到/ragflow端点
            xhr.open('POST', '/ragflow');
            xhr.send(formData);
        }

        // 新增：更新上传历史列表显示
        function updateUploadedFilesList() {
            uploadedFilesList.innerHTML = '';
            uploadedFiles.forEach(fileName => {
                const fileItem = document.createElement('div');
                fileItem.className = 'uploaded-file-item';
                fileItem.textContent = fileName;
                uploadedFilesList.appendChild(fileItem);
            });
        }

        function showStatus(message, type) {
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';

            // 错误或成功消息3秒后自动隐藏
            if (type === 'error' || type === 'success') {
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 3000);
            }
        }
    </script>
</body>

</html>